package cn.hxzy.zyicon.service.impl;

import cn.hxzy.zyicon.entity.Icon;
import cn.hxzy.zyicon.entity.vo.PageBean;
import cn.hxzy.zyicon.repository.IconRepository;
import cn.hxzy.zyicon.service.IconService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;

import java.util.Optional;

@Service("iconService")
public class IconServiceImpl implements IconService {
    @Autowired
    private IconRepository iconRepository;

    @Override
    public PageBean<Icon> findAll(PageBean<Icon> pageBean) {
        Pageable pageable = PageRequest.of(pageBean.getPage() - 1, pageBean.getSize(), Sort.by(Sort.Order.desc("createTime")));
        Page<Icon> all = iconRepository.findAll(pageable);
        pageBean.setList(all.getContent());
        pageBean.setCount(all.getTotalElements());
        pageBean.setPageCount(all.getTotalPages());
        return pageBean;
    }

    @Override
    public void save(Icon icon) {
        iconRepository.save(icon);
    }

    @Override
    public void delete(Integer id) {
        iconRepository.deleteById(id);
    }

    @Override
    public Icon findById(Integer id) {
        Optional<Icon> byId = iconRepository.findById(id);
        if (byId.isPresent()) {
            return byId.get();
        }
        return null;
    }

    @Override
    public PageBean<Icon> findIconByNameLike(String searchName, PageBean<Icon> iconPageBean) {
        searchName="%"+searchName+"%";
        Pageable pageable = PageRequest.of(iconPageBean.getPage() - 1, iconPageBean.getSize(), Sort.by(Sort.Order.desc("createTime")));
        Page<Icon> all= iconRepository.findUserByNameLike(pageable,searchName);
        iconPageBean.setList(all.getContent());
        iconPageBean.setCount(all.getTotalElements());
        iconPageBean.setPageCount(all.getTotalPages());
        return iconPageBean;

    }

    @Override
    public void update(Icon icon) {
     iconRepository.save(icon);
    }
}
